import router from "../router"
import store from "../store"
import cookie from "@utils/store/cookie"
import { isWeixin } from "@utils"

export const LOGIN_BACK_URL = "login_back_url"
export const WXMP_APPID = "wxeb99498a302ac0f5"

export function toLogout() {
  console.log("toLogout")
  store.dispatch("LOGOUT")
}

export function setLoginBackUrl(url) {
  cookie.set(LOGIN_BACK_URL, url)
}

export function toLoginPage() {
  router.push({ path: '/relogin' })
}

export function toLogin(push = false, backUrl = undefined) {
  store.commit("LOGOUT")
  var loginBackUrl = backUrl || cookie.get(LOGIN_BACK_URL)
  const { fullPath, name } = router.currentRoute
  if (!loginBackUrl) {
    loginBackUrl = backUrl || fullPath
  }

  console.log('toLogin, push=' + push + ', loginBackUrl=' + loginBackUrl)
  if (loginBackUrl.includes('/login') || loginBackUrl.includes('/relogin') || loginBackUrl.includes('/logout')) {
    loginBackUrl = '/'
  }
  cookie.set(LOGIN_BACK_URL, loginBackUrl)

  if (isWeixin()) {
    const href = getAuthUrl(WXMP_APPID)
    location.href = href
  } else {
    if (name !== "Login") {
      push
        ? router.push({ path: "/login" })
        : router.replace({ path: "/login" })
    }
  }
}

/*
 * 提示：redirect_uri 的域名，需要在微信公众号【网页授权获取用户基本信息】中设置，
 * 否则会提示【redirect_uri参数错误】
 */
function getAuthUrl(appId) {
  const redirectUri = encodeURIComponent(
      `${location.origin}/auth/` +
      encodeURIComponent(
        encodeURIComponent(
          cookie.has(LOGIN_BACK_URL)
            ? cookie.get(LOGIN_BACK_URL)
            : location.pathname + location.search
        )
      )
  )
  const state = encodeURIComponent(
    ("" + Math.random()).split(".")[1] + ""
  )
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`
}
